package com.itheima.auth;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private String type;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        logger.info("登录失败");

        if ("json".equalsIgnoreCase(this.type)|| "json".equalsIgnoreCase(request.getParameter("type"))) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            String message = exception.getMessage();
            if(message.equals("UserDetailsService returned null, which is an interface contract violation")) message="用户名或密码不存在";
            response.getWriter().write("{\"message\":\""+message+"\",\"flag\":false}");
        }else{
            request.setAttribute("error", exception.getMessage());
            super.setDefaultFailureUrl("/login.jsp");
            super.setUseForward(true);
            super.onAuthenticationFailure(request, response, exception);
        }
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}
